如果說可以讓目前專案更好的地方,
另一個部分就是在與資料庫連連接改使用 Connection Pool 了。
讓我們繼續看下去吧~
以下為有關 Connection Pool 維基百科的說明:
In software engineering, a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required.[1] Connection pools are used to enhance the performance of executing commands on a database. Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources. In connection pooling, after a connection is created, it is placed in the pool and it is used again so that a new connection does not have to be established. If all the connections are being used, a new connection is made and is added to the pool. Connection pooling also cuts down on the amount of time a user must wait to establish a connection to the database.
因為直接與資料庫拿取資料,其實是一件很好效能的事情,
所以我們可以在中間做一個緩存的機制,讓連線留在池子裡面,減少每次都要重新連線的時間與資源的消耗。
接下來我們就來調整我們之前寫過直接與 MySQL 取得資料的程式吧!
config\mysqlConnection.js
檔案嗎? 現在要改為使用 Connection Pool 連線。
將 mysql.createConnection()
改為 mysql.createPool()
// config\mysqlConnection.js
async function mysqlConnection() {
try {
// 建立與數據庫(使用連接池)
const pool = await mysql.createPool({
connectionLimit: 10, // 設定最大連線數
host: process.env.MYSQL_HOSTNAME,
port: 3306,
user: process.env.MYSQL_USERNAME,
password: process.env.MYSQL_PASSWORD,
database: 'book'
})
return pool.getConnection() // 返回使用連接池連接對象
} catch (error) {
console.error('連接數據庫時出現錯誤:', error)
}
}
return 改為 return pool.getConnection()
另外在結束連線時,將 connection.end()
改為 connection.release()
// routes\modules\book.js
router.get('/', async (req, res) => {
try {
// 建立與數據庫的連接(使用連接池)
const connection = await mysqlConnection()
await connection.query('SELECT * FROM `booktest`')
// 關閉連接
connection.release()
} catch (error) {
console.error('連接數據庫時出現錯誤:', error)
}
res.render('page',{'text': 'Get a book'})
})
是不是很簡單!
微微地調整就完成使用 Connection Pool 連線囉!
參考資料: